import React, {useEffect, useState} from 'react'
import {
	Space,
	Button,
	Table,
	Pagination,
	message,
	Modal,
	Form,
	Input,
	Radio,
} from 'antd'
import moment from 'moment'
import {history} from 'umi'
import {
	ArrowDownOutlined,
} from '@ant-design/icons'
import SearchForm from '@/components/SearchForm'
// import Table from '@/components/Table';
import { PageType} from '../constant'
import ExportExcl from './impoart'

import Styles from './index.less'

import {
	getFirstChannelType,
} from '@/service/merchantCenter/channelRule'
import {getAllCitys, getCompany} from '@/service/common'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {translateDataToTree} from '@/utils/common'
import {
	getDitchsettleaccountsList,
	initiateAudit,
	processAuditSuccess,
} from '@/service/merchantCenter/channelSettlement'
import {getDictsByKeys} from '@/service/common/dict'
import {downloadDocumentUrl} from '@/service/common/download'
import Permissions from '@/components/Permissions'

// const data = [
// 	{id: '1', name: '渠道sp'},
// 	{id: '2', name: '车司'},
// 	{id: '3', name: '自营-BD'},
// 	{id: '4', name: '自营-司推司'},
// 	{id: '5', name: '自营-普推司'},
// ]

export default function List({user}: any) {
	// const [dataList, setDataList] = useState<any[]>([{ id: '33' }]);
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [tableList, setTableList] = useState<any[]>([])
	const [loading, setLoading] = useState(false)
	const [formData, setFormData] = useState({})

	const [citysList, setCitysList] = useState<any[]>([])

	const [subjectList, setSubjectList] = useState([])
	// const [orgList, setOrgList] = useState([])
	const [importExcl, setImportExcl] = useState(false) // 导入弹框
	const [channelTypeOneType, setChannelTypeOneType] = useState([])
	const [formItem, setFormItem] = useState()

	// const [leaseTypes, setLeaseTypes] = useState([])

	const getKeyList = () => {
		getDictsByKeys({
			dictKeys: ['order_rent_type'],
		}).then((res: any) => {
			if (res?.data?.length) {
				res.data.forEach((item: any) => {
					if (item.name === 'order_rent_type') {
						// setLeaseTypes(item.listDicts)
					}
				})
			}
		})
	}

	useEffect(() => {
		getKeyList()
	}, [])

	const [form] = Form.useForm()
	/** 获取所属公司数据 */
	const onCompany = () => {
		// eslint-disable-next-line react/destructuring-assignment
		getCompany({merchantId: user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				// setCompanyData(list as any);
				// setOrgList(list)
			}
		})
	}

	const getChannelTypeOneType = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.data?.length) {
				setChannelTypeOneType(res.data)
			}
		})
	}

	const formItems = [
		{
			type: 'group',
			key: 'group',
			groupItems: [
				{
					type: 'input',
					label: '渠道奖励ID',
					name: 'rewardsId',
					key: 'rewardsId',
					placeholder: '请输入',
				},
				{
					type: 'input',
					label: ' 渠道ID/名称',
					name: 'ditchName',
					key: 'ditchName',
					placeholder: '请输入',
				},
				{
					type: 'select',
					label: 'AMC一级渠道类型',
					name: 'firstLevelType',
					key: 'firstLevelType',
					title: 'text',
					items: channelTypeOneType.map((item: any) => ({
						value: item.type,
						text: item.valueName,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					label: 'AMC二级渠道类型',
					name: 'secondLevelType',
					key: 'secondLevelType',
					placeholder: '请选择',
					title: 'text',
					items: [
						{id: '1', name: '渠道sp'},
						{id: '2', name: '车司'},
						{id: '3', name: '自营-BD'},
						{id: '4', name: '自营-司推司'},
						{id: 1, name: '自营-普推司'},
					].map((item: any) => ({
						value: item.id,
						text: item.name,
					})),
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					placeholder: '请选择',
					items: citysList,
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
				},
				{
					type: 'select',
					label: '审批状态',
					name: 'auditStatus',
					key: 'auditStatus',
					title: 'text',
					placeholder: '请选择',
					items: [
						{value: 1, name: '待审核'},
						{value: 2, name: '审核中'},
						{value: 3, name: '审核通过'},
						{value: 4, name: '审核拒绝'},
					].map((item: any) => ({
						value: item.value,
						text: item.name,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					label: '补扣费审批状态',
					name: 'supplementaryCostStatus',
					key: 'supplementaryCostStatus',
					title: 'text',
					placeholder: '请选择',
					items: [
						{value: '0', name: '无补扣'},
						{value: '1', name: '待审核'},
						{value: '2', name: '审核中'},
						{value: '3', name: '审核通过'},
						{value: '4', name: '审核拒绝'},
					].map((item: any) => ({
						value: item.value,
						text: item.name,
					})),
				},
				{
					type: 'time',
					subtype: 'month',
					valueTime: moment(),
					allowClear: false,
					label: '结算月份',
					name: 'settlementMouth',
					key: 'settlementMouth',
				},
				{
					type: 'dateRange',
					label: '创建时间 ',
					name: 'date',
					key: 'date',
					placeholder: '请输入',
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'select',
					label: '主体',
					name: 'subject',
					key: 'subject',
					title: 'text',
					items: subjectList.map((item: any) => ({
						value: item.id,
						text: item.merchantName,
					})),
				},
				{
					type: 'select',
					label: '结算状态',
					name: 'settlementStatus',
					key: 'settlementStatus',
					title: 'text',
					placeholder: '请选择',
					items: [
						{value: '1', name: '未结算'},
						{value: '2', name: '已结算'},
					].map((item: any) => ({
						value: item.value,
						text: item.name,
					})),
				},
				{},
			],
		},
	]

	const openDetail = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/channelSettlement/detail',
			query: {
				pageType: PageType.Detail,
				id: record.id,
				leaseType: record.leaseType,
				processId:record.processId,
				orgId:record.orgId
			},
		})
	}

	const openEditPage = (record: any) => {
		const isEdit = (
			record.supplementaryCostStatus === 4 || record.auditStatus === 4
		).toString()
		history.push({
			pathname: '/merchantCenter/channelSettlement/edit',
			query: {
				pageType: PageType.Edit,
				id: record.id,
				isEdit,
			},
		})
	}

	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value
		if (values?.date) {
			values.startTime = moment(values.date[0]).format('YYYY-MM-DD')
			values.endTime = moment(values.date[1]).format('YYYY-MM-DD')
			delete values.date
		}
		if (values.settlementMouth) {
			values.settlementMouth = moment(values.settlementMouth).format(
				'YYYY-MM',
			)
		}
		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}
		setParams(newPagination)
		values = {
			...values,
			...newPagination,
		}
		const res = await getDitchsettleaccountsList(values)
		if (res?.data) {
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				setTableList(res.data?.records || [])
			}
		}
		setLoading(false)
	}

	const onFinish = (values: any) => {
		setFormItem(values)
		getTabelValue(values)
		// eslint-disable-next-line no-param-reassign
	}

	// 搜索重置
	const onReset = () => {
		getTabelValue({})
	}

	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data || [])
			}
		})
	}

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		getSubjectFun()
		onCompany()
		getChannelTypeOneType()
		getTabelValue(formData)
	}, [])

	const paginationChange = (current: number, size: number) => {
		getTabelValue(formData, {
			current,
			size,
		})
	}

	const Colunms: any[] = [
		{title: '渠道奖励id', dataIndex: 'rewardsIds', align: 'center'},
		{title: '费用发生月份', dataIndex: 'expenseMouth', align: 'center'},
		{title: '主体id ', dataIndex: 'subjectId', align: 'center'},
		{title: '主体', dataIndex: 'subjectName', align: 'center'},
		{title: '公司id', dataIndex: 'orgId', align: 'center'},
		{title: '公司名称', dataIndex: 'orgName', align: 'center'},
		{title: '城市id', dataIndex: 'cityId', align: 'center'},
		{title: '城市', dataIndex: 'cityName', align: 'center'},
		{
			title: '租赁类型',
			dataIndex: 'leaseTypename',
			align: 'center',
			// render: (text: any) => {
			// 	const obj: any = leaseTypes.find(
			// 		(item: any) => item.value === text,
			// 	)
			// 	return obj?.valueName
			// },
		},
		{
			title: 'AMC一级渠道类型 ',
			dataIndex: 'firstLevelTypeStr',
			align: 'center',
			// render: (text: any) =>
			// 	channelTypeOneType?.map((res: any) => {
			// 		if (text === res?.type) {
			// 			return <span>{res?.valueName}</span>
			// 		}
			// 	}),
		},
		{
			title: 'AMC二级渠道类型',
			dataIndex: 'secondLevelTypeStr',
			align: 'center',
			// render: (text: any) =>
			// 	data?.map((res: any) => {
			// 		if (text == res?.id) {
			// 			return <span>{res?.name}</span>
			// 		}
			// 	}),
		},
		{title: '渠道id', dataIndex: 'ditchId', align: 'center'},
		{title: '渠道名称', dataIndex: 'ditchName', align: 'center'},
		{
			title: '渠道费用总额',
			dataIndex: 'amountSum',
			align: 'center',
		},
		{
			title: '总有效拉新订单量',
			dataIndex: 'effectiveLeaseTermTotalCount',
			align: 'center',
		},
		{
			title: '总租期',
			dataIndex: 'effectiveOrderTotalCount',
			align: 'center',
		},
		{title: '单期拉新费', dataIndex: 'pullFeeTotal', align: 'center'},
		{title: '税率', dataIndex: 'taxRate', align: 'center'},
		{
			title: '渠道费用总额（不含税）',
			dataIndex: 'noIncludedFee',
			align: 'center',
		},
		{
			title: '拉新订单数量（系统自动）',
			dataIndex: 'orderCount',
			align: 'center',
		},
		{
			title: '有效拉新订单量（系统自动）',
			dataIndex: 'effectiveOrderCount',
			align: 'center',
		},
		{
			title: '有效拉新订单总租期（系统自动）',
			dataIndex: 'effectiveLeaseTermSum',
			align: 'center',
		},
		{
			title: '单期拉新费（系统自动）',
			dataIndex: 'pullFee',
			align: 'center',
		},
		{
			title: '拉新结算总金额（系统自动）',
			dataIndex: 'effectivePullFeeTotalSum',
			align: 'center',
		},
		{
			title: '冲单奖励金额',
			dataIndex: 'punchOrderAmount',
			align: 'center',
		},
		{title: 'BD跟单费', dataIndex: 'bdCost', align: 'center'},
		{
			title: '补扣费总金额',
			dataIndex: 'supplementaryCost',
			align: 'center',
		},
		{
			title: '补扣订单量',
			dataIndex: 'supplementaryCount',
			align: 'center',
		},
		{
			title: '补扣总期数',
			dataIndex: 'deductionRateTerm',
			align: 'center',
		},
		{
			title: '结算状态',
			dataIndex: 'settlementStatus',
			align: 'center',
			render: (text: any) => ['', '未结算', '已结算'][text],
		},
		{title: '结算时间', dataIndex: 'settlementTime', align: 'center'},
		{
			title: '审批状态',
			dataIndex: 'auditStatusStr',
			align: 'center',
			// render: (text: any) =>
			// 	['', '待审核', '审核中', '审核通过', '审核拒绝'][text],
		},
		{
			title: '补扣费审批状态',
			dataIndex: 'supplementaryCostStatusStr',
			align: 'center',
			// render: (text: any) =>
			// 	['无补扣', '待审核', '审核中', '审核完成', '审核驳回'][text],
		},

		{
			title: '操作',
			width: 200,
			align: 'center',
			fixed: 'right',
			render: (ffield: string, record: any) => {
				// console.log(record)
				const {
					leaseType,
					auditStatus,
					supplementaryCostStatus,
					auditBut,
					supplementaryAuditBut,
				} = record
				let showx = false
				let showb = false
				let showj = false
				let showk = false
				let showf = false
				if (leaseType !== 1) {
					if (auditStatus === 1 || auditStatus === 4) {
						showx = true
						showf = true
					}
					if (auditStatus === 2 && auditBut === 1) {
						showx = true
						showj = true
					}
					if (auditStatus === 3) {
						showx = true
					}
				}
				if (leaseType === 1) {
					if (supplementaryCostStatus === 0) {
						if (auditStatus === 1) {
							showx = true
							showf = true
							showb = true
						}
						if (auditStatus === 2 && auditBut === 1) {
							showx = true
							showj = true
						}
						if (auditStatus === 3) {
							showx = true
						}
						if (auditStatus === 4) {
							showx = true
							showf = true
							showb = true
						}
					}
					if (supplementaryCostStatus === 1) {
						if (auditStatus === 1 && supplementaryAuditBut === 1) {
							showx = true
							showk = true
						}
						if (auditStatus === 4 && supplementaryAuditBut === 1) {
							showx = true
							showk = true
						}
					}
					if (supplementaryCostStatus === 2) {
						if (auditStatus === 1 && supplementaryAuditBut === 1) {
							showx = true
							showk = true
						}
						if (auditStatus === 4 && supplementaryAuditBut === 1) {
							showx = true
							showk = true
						}
					}
					if (supplementaryCostStatus === 3) {
						if (auditStatus === 1) {
							showx = true
							showf = true
						}
						if (auditStatus === 2 && auditBut === 1) {
							showx = true
							showj = true
						}
						if (auditStatus === 3) {
							showx = true
						}
						if (auditStatus === 4) {
							showx = true
							showf = true
							showb = true
						}
					}
					if (supplementaryCostStatus === 4) {
						if (auditStatus === 1) {
							showx = true
							showb = true
						}
					}
					if (auditBut === 1) {
						showj = true
					}
					if (supplementaryAuditBut === 1) {
						showk = true
					}
				}
				showx = true
				return (
					<Space size={12}>
						{showx && (
							<Permissions permissionID="amc_merchantCenter_channelSettlement_detail">
								<Button
									type="link"
									onClick={() => openDetail(record)}>
									详情
								</Button>
							</Permissions>
						)}
						{showb && (
						<Permissions permissionID="amc_merchantCenter_channelSettlement_edit">
							<Button
								type="link"
								onClick={() => openEditPage(record)}>
								编辑补扣费
							</Button>
						</Permissions>
						 )}
						{showj && (
							<Permissions permissionID="amc_merchantCenter_channelSettlement_auditj">
								<Button
									type="link"
									onClick={() => {
										history.push({
											pathname:
												'/merchantCenter/channelSettlement/detail',
											query: {
												pageType: 'audit1',
												id: record.id,
												type: '1',
												leaseType: record.leaseType,
											},
										})
									}}>
									结算审核
								</Button>
							</Permissions>
						)}
						{showk && (
							<Permissions permissionID="amc_merchantCenter_channelSettlement_audit">
								<Button
									type="link"
									onClick={() => {
										history.push({
											pathname:
												'/merchantCenter/channelSettlement/detail',
											query: {
												pageType: 'audit2',
												id: record.id,
												type: '2',
												leaseType: record.leaseType,
											},
										})
									}}>
									审核
								</Button>
							</Permissions>
						)}
						{showf && (
							<Permissions permissionID="amc_merchantCenter_channelSettlement_initiateaudit">
								<Button
									type="link"
									onClick={() => {
										initiateAudit({id: record.id}).then(
											(res: any) => {
												if (res.success) {
													message.success(res.msg)
													getTabelValue(
														formData,
														params,
													)
												}
											},
										)
									}}>
									发起审核
								</Button>
							</Permissions>
						)}
					</Space>
				)
			},
		},
	]
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

	const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
		setSelectedRowKeys(newSelectedRowKeys)
	}

	const rowSelection: any = {
		selectedRowKeys,
		onChange: onSelectChange,
		// getCheckboxProps: (record: any) => ({
		//   disabled: record.key === 1, // Column configuration not to be checked
		//   // name: record.name,
		// }),
	}

	const [aType, setAType] = useState('')

	const [visible, setVisible] = useState(false)
	const onAuditSave = async () => {
		const va = await form.validateFields()
		// const id = selectRows.map((item) => item.id)
		const param = {
			ids: selectedRowKeys,
			...va,
		}
		if (aType === '结算') {
			param.type = 1
		}
		if (aType === '补扣费') {
			param.type = 2
		}
		processAuditSuccess(param)
			.then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
					setSelectedRowKeys([])
					setVisible(false)
				}
			})
			.catch(() => {

			})
	}

	const sunChange = (value: any) => {
		if (value) {
			setImportExcl(false)
		}
	}

	return (
		<div className={Styles.list}>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '90px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={formItems}
					onFinish={onFinish}
					onReset={onReset}
				/>
			</div>
			<div className={Styles.content}>
				<div className={Styles.btnListBox}>
					<div>
						<Space size={12}>
							{/* <Button
								onClick={() => {
									history.push(
										'/merchantCenter/channelSettlement/add',
									)
								}}
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small">
								新增
							</Button> */}
							<Permissions permissionID="amc_merchantCenter_channelSettlement_batchauditj">
								<Button
									onClick={() => {
										setAType('结算')
										setVisible(true)
									}}
									disabled={selectedRowKeys.length === 0}
									type="primary"
									ghost
									size="small">
									批量审批结算
								</Button>
							</Permissions>

							<Permissions permissionID="amc_merchantCenter_channelSettlement_batchaudit">
								<Button
									onClick={() => {
										setAType('补扣费')
										setVisible(true)
									}}
									type="primary"
									ghost
									disabled={selectedRowKeys.length === 0}
									size="small">
									批量审批补扣费
								</Button>
							</Permissions>

							<Permissions permissionID="amc_merchantCenter_channelSettlement_export">
								<Button
									icon={<ArrowDownOutlined />}
									className={Styles.import}
									ghost
									onClick={() => {
										downloadDocumentUrl({
											resourceId: '176',
											queryDesc:
												'渠道结算列表导出,resourceId:176',
											queryParam: formItem,
										})
									}}
									size="small">
									导出
								</Button>
							</Permissions>
						</Space>
					</div>
				</div>
				<Table
					columns={Colunms}
					dataSource={tableList}
					pagination={false}
					rowKey={(rocode: any) => rocode?.id}
					rowSelection={rowSelection}
					loading={loading}
					scroll={{x: 5000, y: 500}}
				/>
				<div
					style={{
						paddingTop: '12px',
						display: 'flex',
						justifyContent: 'end',
					}}>
					<Pagination
						defaultCurrent={1}
						current={params.current}
						total={total}
						// eslint-disable-next-line no-shadow
						showTotal={(total, range) =>
							`第  ${range[0]} - ${range[1]} 条 / 总共 ${total} 条`
						}
						showSizeChanger
						showQuickJumper
						onChange={paginationChange}
					/>
				</div>
			</div>

			<Modal
				title={`批量审核${aType}`}
				open={visible}
				onCancel={() => {
					setVisible(false)
					setAType('')
				}}
				width={500}
				onOk={onAuditSave}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={form}>
					<Form.Item
						label="审核状态"
						name="pass"
						rules={[{required: true}]}>
						<Radio.Group>
							<Radio value={1}>审核通过</Radio>
							<Radio value={2}>审核驳回</Radio>
						</Radio.Group>
					</Form.Item>
					<Form.Item
						label="处理意见"
						name="message"
						rules={[
							{
								validator(rule, value) {
									return value?.length <= 200
										? Promise.resolve('')
										: Promise.reject(
												new Error(
													'处理意见文字长度不能大于200',
												),
										  )
								},
							},
						]}>
						<Input.TextArea
							rows={3}
							placeholder="请输入处理意见,不超过200个字"
						/>
					</Form.Item>
				</Form>
			</Modal>
			<ExportExcl info={importExcl} sunchange={sunChange} />
		</div>
	)
}
